package com.xxy.book.service;

import com.xxy.book.dao.UserMapper;
import com.xxy.book.dto.UserDetailDTO;
import com.xxy.book.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author Xu XianYun
 * @Date 2023-01-06
 * @Description
 */
@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("开始登录验证，用户名: {}", username);
        //System.out.println("开始登录验证，用户名为: " + username);

        //根据用户名验证用户
        User user = userMapper.selectUserByName(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在，登录失败。");
        }

        //构建 UserDetail 对象
        UserDetailDTO userDetailDTO = new UserDetailDTO();
        userDetailDTO.setUsername(user.getUsername());
        userDetailDTO.setPassword(user.getPassword());

        //由于数据库表设计时没有设计角色表，无法从数据库查询角色列表，所以在 UserDetailDTO 手动模拟出一个角色列表
        return userDetailDTO;
    }
}
